//获取websocket模块
const SocketServer = require('ws').Server;

var wss;
var client = {};
var logLost = [];

/**
 * 初始化socket服务
 * @param opt
 * @param finishedCb
 * @returns {WebSocketServer}
 */
function initWs(opt, finishedCb) {
  wss = new SocketServer({
    port: opt.wsPort
  });
  if(typeof finishedCb === 'function') finishedCb();

  wss.on('connection', function (ws) {
    ws.on('message', function (message) {
      if(message === 'SIGN_PAGE_LOG'){
        // 首次连接 页面，缓存ws对象
        client['SIGN_PAGE_LOG'] = ws;
        // logLost: [
        //   '{"msg":[111,"sss",{"name":"ss","age":1},[1,"212",{"s":1}]],"opt":{}}',
        //   '{"msg":[222],"opt":{}}',
        //   '{"msg":[333],"opt":{}}',
        //   '{"msg":[444],"opt":{}}'
        // ]
        ws.send(JSON.stringify(logLost));
      } else if(message === 'PAGE_LOG_CLEAR'){
        // 清除数据
        client['SIGN_PAGE_LOG'].send(message);
        logLost = [];
      } else if(client['SIGN_PAGE_LOG']){
        // 指定页面发送数据
        // message: {"msg":[555],"opt":{}}
        logLost.push(message);
        client['SIGN_PAGE_LOG'].send(message);
      } else {
        // 暂不处理
      }
    })

  });

  return wss;
}


function getWs(){
  return wss;
}


module.exports = {
  initWs,
  getWs
}
